<template>
  <div class="permission-page">
    <div class="card-header">
      <h2>权限管理</h2>
      <div class="header-actions">
        <el-button type="primary" @click="handleAddPermission">
          <el-icon><Plus /></el-icon>
          新增权限
        </el-button>
        <el-button @click="showBatchDeleteConfirm" :disabled="selectedPermissions.length === 0">
          <el-icon><Delete /></el-icon>
          批量删除
        </el-button>
      </div>
    </div>

    <el-card class="search-form">
      <el-form :model="searchForm" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="权限名称">
              <el-input v-model="searchForm.perm_name" placeholder="请输入权限名称" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="权限代码">
              <el-input v-model="searchForm.perm_code" placeholder="请输入权限代码" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="所属模块">
              <el-select v-model="searchForm.module_id" placeholder="请选择模块">
                <el-option label="全部" value="" />
                <el-option
                  v-for="module in moduleList"
                  :key="module.module_id"
                  :label="module.module_name"
                  :value="module.module_id.toString()"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="权限类型">
              <el-select v-model="searchForm.perm_type" placeholder="请选择权限类型">
                <el-option label="全部" value="" />
                <el-option
                  v-for="type in PERMISSION_TYPES"
                  :key="type.value"
                  :label="type.label"
                  :value="type.value.toString()"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="状态">
              <el-select v-model="searchForm.is_active" placeholder="请选择状态">
                <el-option label="全部" value="" />
                <el-option label="启用" value="1" />
                <el-option label="禁用" value="0" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="18" class="action-buttons">
            <el-form-item>
              <el-button type="primary" @click="handleSearch">查询</el-button>
              <el-button @click="handleReset">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <el-card class="data-table">
      <el-table
        v-loading="loading"
        :data="permissionList"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="perm_id" label="权限ID" width="80" />
        <el-table-column prop="perm_name" label="权限名称" />
        <el-table-column prop="perm_code" label="权限代码" />
        <el-table-column prop="module_id" label="所属模块">
          <template #default="scope">
            {{ getModuleName(scope.row.module_id) }}
          </template>
        </el-table-column>
        <el-table-column prop="perm_type" label="权限类型">
          <template #default="scope">
            {{ PERMISSION_TYPE_LABELS[scope.row.perm_type] }}
          </template>
        </el-table-column>
        <el-table-column prop="is_active" label="状态" width="100">
          <template #default="scope">
            <el-switch
              v-model="scope.row.is_active"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="sort_order" label="排序" width="80" />
        <el-table-column prop="create_time" label="创建时间" width="180" />
        <el-table-column prop="update_time" label="更新时间" width="180" />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleEditPermission(scope.row)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDeletePermission(scope.row.perm_id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑权限对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEditing ? '编辑权限' : '新增权限'"
      width="600px"
    >
      <el-form
        ref="permissionFormRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
      >
        <el-form-item label="权限名称" prop="perm_name">
          <el-input v-model="formData.perm_name" placeholder="请输入权限名称" />
        </el-form-item>
        <el-form-item label="权限代码" prop="perm_code">
          <el-input v-model="formData.perm_code" placeholder="请输入权限代码" />
        </el-form-item>
        <el-form-item label="所属模块" prop="module_id">
          <el-select v-model="formData.module_id" placeholder="请选择所属模块">
            <el-option
              v-for="module in moduleList"
              :key="module.module_id"
              :label="module.module_name"
              :value="module.module_id.toString()"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="权限类型" prop="perm_type">
          <el-select v-model="formData.perm_type" placeholder="请选择权限类型">
            <el-option
              v-for="type in PERMISSION_TYPES"
              :key="type.value"
              :label="type.label"
              :value="type.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="权限描述">
          <el-input
            v-model="formData.description"
            type="textarea"
            placeholder="请输入权限描述"
            :rows="3"
          />
        </el-form-item>
        <el-form-item label="排序号">
          <el-input-number
            v-model="formData.sort_order"
            placeholder="请输入排序号"
            :min="0"
            controls-position="right"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="是否启用">
          <el-switch
            v-model="formData.is_active"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 批量删除确认对话框 -->
    <el-dialog
      v-model="batchDeleteDialogVisible"
      title="批量删除确认"
      width="400px"
      :show-close="false"
    >
      <p>确定要删除选中的 {{ selectedPermissions.length }} 个权限吗？</p>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="batchDeleteDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="handleBatchDelete">确定删除</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import type { FormInstance } from 'element-plus';
import { useIamPermissionStore } from '../../stores/iam/IamPermissionStore';
import { useIamModuleStore } from '../../stores/iam/IamModuleStore';
import type { Permission } from '../../stores/iam/IamPermissionStore';
import type { Module } from '../../stores/iam/IamModuleStore';
import { Plus, Delete } from '@element-plus/icons-vue';

// 常量定义
const PERMISSION_TYPES = [
  { value: 1, label: '菜单权限' },
  { value: 2, label: '操作权限' },
  { value: 3, label: '数据权限' }
];

const PERMISSION_TYPE_LABELS: Record<number, string> = {
  1: '菜单权限',
  2: '操作权限',
  3: '数据权限'
};

// Store实例
const permissionStore = useIamPermissionStore();
const moduleStore = useIamModuleStore();

// 响应式数据
const loading = ref(false);
const dialogVisible = ref(false);
const batchDeleteDialogVisible = ref(false);
const isEditing = ref(false);
const selectedPermissions = ref<number[]>([]);
const permissionFormRef = ref<FormInstance>();

const searchForm = reactive({
  perm_name: '',
  perm_code: '',
  module_id: '',
  perm_type: '',
  is_active: ''
});

const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 表单数据和验证规则
const formData = reactive({
  perm_id: 0,
  perm_name: '',
  perm_code: '',
  description: '',
  module_id: '',
  perm_type: 1,
  sort_order: 0,
  is_active: 1,
  is_deleted: 0
});

const formRules = reactive({
  perm_name: [
    { required: true, message: '请输入权限名称', trigger: 'blur' },
    { min: 2, max: 50, message: '权限名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  perm_code: [
    { required: true, message: '请输入权限代码', trigger: 'blur' },
    { min: 2, max: 100, message: '权限代码长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  module_id: [
    { required: true, message: '请选择所属模块', trigger: 'change' }
  ],
  perm_type: [
    { required: true, message: '请选择权限类型', trigger: 'change' }
  ]
});

// 计算属性
const permissionList = computed(() => {
  return permissionStore.permissionList;
});

const moduleList = computed(() => {
  return moduleStore.moduleList;
});

// 生命周期
onMounted(() => {
  fetchData();
  fetchModules();
});

// 方法
const fetchData = async () => {
  loading.value = true;
  try {
    await permissionStore.fetchPermissionList({
      page: pagination.currentPage,
      pageSize: pagination.pageSize,
      ...searchForm
    });
    pagination.total = permissionStore.totalCount;
  } catch (error) {
    ElMessage.error('获取权限列表失败');
    console.error('获取权限列表失败:', error);
  } finally {
    loading.value = false;
  }
};

const fetchModules = async () => {
  try {
    await moduleStore.fetchModuleList();
  } catch (error) {
    ElMessage.error('获取模块列表失败');
    console.error('获取模块列表失败:', error);
  }
};

const handleSearch = () => {
  pagination.currentPage = 1;
  fetchData();
};

const handleReset = () => {
  Object.assign(searchForm, {
    perm_name: '',
    perm_code: '',
    module_id: '',
    perm_type: '',
    is_active: ''
  });
  pagination.currentPage = 1;
  fetchData();
};

const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  fetchData();
};

const handleCurrentChange = (current: number) => {
  pagination.currentPage = current;
  fetchData();
};

const handleSelectionChange = (selection: Permission[]) => {
  selectedPermissions.value = selection.map((item: Permission) => item.perm_id);
};

const handleAddPermission = () => {
  isEditing.value = false;
  Object.assign(formData, {
    perm_id: 0,
    perm_name: '',
    perm_code: '',
    description: '',
    module_id: '',
    perm_type: 1,
    sort_order: 0,
    is_active: 1,
    is_deleted: 0
  });
  dialogVisible.value = true;
};

const handleEditPermission = (row: Permission) => {
  isEditing.value = true;
  Object.assign(formData, {
    perm_id: row.perm_id,
    perm_name: row.perm_name,
    perm_code: row.perm_code,
    description: row.description || '',
    module_id: row.module_id?.toString() || '',
    perm_type: row.perm_type,
    sort_order: row.sort_order || 0,
    is_active: row.is_active !== undefined ? row.is_active : 1,
    is_deleted: row.is_deleted || 0
  });
  dialogVisible.value = true;
};

const handleSubmit = async () => {
  try {
    if (!permissionFormRef.value) return;

    await permissionFormRef.value.validate();

    // 确保 module_id 是数字类型
    const submitData = {
      ...formData,
      module_id: formData.module_id ? Number(formData.module_id) : undefined
    };

    if (isEditing.value) {
      await permissionStore.updatePermission(submitData.perm_id, submitData as Partial<Permission>);
      ElMessage.success('更新权限成功');
    } else {
      const addData = {
        perm_name: formData.perm_name,
        perm_code: formData.perm_code,
        description: formData.description,
        module_id: formData.module_id ? Number(formData.module_id) : undefined,
        perm_type: formData.perm_type,
        is_active: formData.is_active,
        sort_order: formData.sort_order
      };
      await permissionStore.addPermission(addData as Omit<Permission, 'perm_id'>);
      ElMessage.success('添加权限成功');
    }

    dialogVisible.value = false;
    fetchData();
  } catch (error) {
    ElMessage.error(isEditing.value ? '更新权限失败' : '添加权限失败');
    console.error(isEditing.value ? '更新权限失败:' : '添加权限失败:', error);
  }
};

const handleDeletePermission = async (permId: number) => {
  try {
    await ElMessageBox.confirm('确定要删除该权限吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    await permissionStore.deletePermission(permId);
    ElMessage.success('删除权限成功');
    fetchData();
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除权限失败');
    }
  }
};

const showBatchDeleteConfirm = () => {
  if (selectedPermissions.value.length === 0) {
    ElMessage.warning('请选择要删除的权限');
    return;
  }
  batchDeleteDialogVisible.value = true;
};

const handleBatchDelete = async () => {
  if (selectedPermissions.value.length === 0) {
    ElMessage.warning('请选择要删除的权限');
    return;
  }

  try {
    await permissionStore.batchDeletePermissions(selectedPermissions.value);
    ElMessage.success(`成功删除 ${selectedPermissions.value.length} 个权限`);
    batchDeleteDialogVisible.value = false;
    fetchData();
  } catch (error) {
    ElMessage.error('批量删除权限失败');
    console.error('批量删除权限失败:', error);
  }
};

const handleStatusChange = async (row: Permission) => {
  try {
    await permissionStore.updatePermission(row.perm_id, {
      is_active: row.is_active
    } as Partial<Permission>);
    ElMessage.success('状态更新成功');
  } catch (error) {
    // 失败时恢复原状态
    row.is_active = row.is_active === 1 ? 0 : 1;
    ElMessage.error('状态更新失败');
    console.error('状态更新失败:', error);
  }
};

const getModuleName = (moduleId?: number | string): string => {
  if (!moduleId) return '-';
  const module = moduleList.value.find((item: Module) => item.module_id === Number(moduleId));
  return module ? module.module_name : '-';
};
</script>

<style scoped>
.permission-page {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-form {
  margin-bottom: 20px;
}

.action-buttons {
  display: flex;
  justify-content: flex-start;
  gap: 10px;
}

.data-table {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>